<template>
  <div class="login">
    <div class="loginHearder">
      <!-- <div class="login-log"></div> -->
    </div>
    <div class="loginContent clearfix">
      <div class="loginContentLeft fl"></div>
      <div class="loginContentRight fr">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <!-- <h3 class="title">后台框架</h3> -->
          <div class="lf_title"></div>
          <h3 class="title">用户登录</h3>
          <el-form-item prop="username" class="mb_form">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
            >
              <svg-icon
                slot="prefix"
                icon-class="user"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="password" class="mb_form">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="password"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="validCode" v-if="captchaEnabled">
            <el-input
              v-model="loginForm.validCode"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="validCode"
                class="el-input__icon input-icon"
              />
            </el-input>
            <div class="login-code">
              <img
                id="loginImgCode"
                :src="`${codeUrl}/api-uaa/v1/validate/code?deviceId=${deviceId}&type=0`"
                :onclick="`this.src='${codeUrl}/api-uaa/v1/validate/code?deviceId=${deviceId}&type=0'`"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox
              v-model="loginForm.rememberMe"
              style="margin: 0px 0px 5px 10px"
              >记住密码</el-checkbox
            >
          </el-form-item>
          <el-form-item style="width: 100%">
            <el-button
              class="loginIn"
              :loading="loading"
              size="medium"
              type="primary"
              style="width: 100%"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right" v-if="register">
              <router-link class="link-type" :to="'/register'"
                >立即注册</router-link
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>版权所有© 2019-2029 科技股份有限公司 </span>
    </div>
  </div>
</template>

<script>
import { getPublicKey, getCodeImg, getTokens } from "@/api/login";
import Cookies from "js-cookie";

import { encrypt, decrypt } from "@/utils/jsencrypt";
import { setToken, removeToken } from "@/utils/auth";
import { guid } from "@/utils/auth";
export default {
  name: "Login",
  data() {
    return {
      codeUrl: process.env.VUE_APP_BASE_API,

      loginForm: {
        username: "",
        password: "",
        grant_type: "password",
        scope: "",
        publicKeyId: "",
        validCode: "",
      },
      deviceId: guid(),
      rememberMe: false,

      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        validCode: [
          { required: true, trigger: "change", message: "请输入验证码" },
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // this.getCode();
    this.getCookie();
  },
  // mounted() {
  //   this.getToken();
  // },
  methods: {
    getToken() {
      // 获取地址栏url
      let url = window.location.href;
      // 在url中匹配code=后面的值
      let code = url.match(/code=(\S*)#/);

      // 如果code不存在，跳转到登录页面
      if (!code) {
        // this.jumpToIndex();
        return;
      }
      let realCode = code[1];
      this.$store.commit("SET_TOKEN", "");
      removeToken();
      this.loginForm = {
        code: realCode,
        grant_type: "authorization_code",
        redirect_uri: "http://localhost:1024",
      };
      getTokens(this.loginForm).then((res) => {
        setToken(res.obj.accessToken);
        this.$store.commit("SET_TOKEN", res.obj.accessToken);
        this.$router.push({ path: "/" });
        
      });
    },
    jumpToIndex() {
      // 打开外部链接, 在当前页面打开 no-referrer
      window.open(
        "http://localhost:8088/api-uaa/v1/oauth/authorize?client_id=zck&response_type=code&scope=all&redirect_uri=http://localhost:1024",
        "_self",
        "noopener noreferrer"
      );
    },

    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },

    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          getPublicKey().then((response) => {
            this.loginForm.password = encodeURIComponent(
              encrypt(this.loginForm.password, response.obj.publicKey)
            );
            this.loginForm.username = encodeURIComponent(
              encrypt(this.loginForm.username, response.obj.publicKey)
            );
            this.loginForm.publicKeyId = response.obj.baseId;
            this.loginForm.deviceId = this.deviceId;

            this.loading = true;
            if (this.rememberMe) {
              Cookies.set("username", encrypt(this.loginForm.username), { expires: 30 });
              Cookies.set("password", encrypt(this.loginForm.password), {
                expires: 30,
              });
              Cookies.set("rememberMe", this.rememberMe, {
                expires: 30,
              });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove("rememberMe");
            }
            console.log(this.loginForm, "000");
            this.$store
              .dispatch("Login", this.loginForm)
              .then(() => {
                // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
                this.$router.push({ path: "/" }).catch(() => {});
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {
                  // this.getCode();
                }
                document.getElementById("loginImgCode").src =
                  this.codeUrl +
                  `api-uaa/v1/validate/code?deviceId=${this.deviceId}&type=0`;
              });
          });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("~@/assets/images/login-bg2.png");
  background-size: 100% 100%;
}
.loginHearder {
  width: 100%;
  height: 90px;
  background: rgba($color: #fff, $alpha: 0.2);
  position: fixed;
  top: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .login-log {
    width: 281px;
    height: 41px;
    background: url("~@/assets/images/login-logo.png") no-repeat center;
    background-size: 100% 100%;
    margin-left: 40px;
  }
}
.loginContent {
  width: 1270px;
  height: 500px;
  position: relative;
  margin-bottom: 70px;
  .loginContentLeft {
    display: none;
    width: 400px;
    height: 500px;
    background: url("~@/assets/images/login-left.jpg") no-repeat center;
    // background-size: cover;
    background-size: 100% 100%;

    box-sizing: border-box;
    margin-right: 94px;
  }
  .loginContentRight {
    width: 420px;
    height: 580px;
    box-sizing: border-box;
    background: linear-gradient(180deg, #ffffff 0%, #e4eeff 100%);
    box-shadow: 0px 0px 15px 1px rgba(220, 231, 250, 0.27);
    border-radius: 10px;
    position: relative;

    .lf_title {
      // border: 1px solid red;
      width: 380px;
      height: 60px;
      position: absolute;
      top: 30px;
      left: 50%;
      transform: translateX(-50%);
      background: url("../assets/images/login-title.png") no-repeat center;
      background-size: 100% 100%;
    }

    .title {
      margin: 60px auto 30px;
      font-size: 24px;
      box-sizing: border-box;
      color: #333;
      font-weight: 700;
      position: relative;
    }

    .login-form {
      width: 100%;
      height: 100%;
      padding: 60px 30px;
      .el-input {
        height: 50px;
        input {
          height: 50px;
          border-radius: 5px;
        }
      }
      .input-icon {
        height: 50px;
        width: 20px;
        margin-left: 15px;
      }
      a {
        color: #0188fe;
        display: inline-block;
        margin-left: 134px;
      }
      .loginIn {
        height: 50px;
        width: 360px;
        background: #3184ff;
        box-shadow: 0px 3px 7px 0px rgba(49, 132, 255, 0.35);
        border-radius: 25px;
        font-weight: bold;
        font-size: 18px;
        color: #ffffff;
      }
      p {
        text-align: center;
        color: red;
      }
    }
    .login-tip {
      font-size: 13px;
      text-align: center;
      color: #bfbfbf;
    }
    .login-code {
      width: 33%;
      height: 50px;
      float: right;
      img {
        cursor: pointer;
        width: 100%;
        height: 100%;
        vertical-align: middle;
      }
    }
  }
}

.el-login-footer {
  height: 60px;
  line-height: 60px;
  position: fixed;
  bottom: 0px;
  width: 100%;
  text-align: center;
  color: #3b424b;
  background: rgba(201, 221, 248, 0.4);
  // font-family: Arial;
  font-size: 14px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 50px;
}
.mb_form {
  margin-bottom: 30px !important;
}

.loginContent .loginContentRight .login-form .el-input input {
  padding-left: 50px;
  font-size: 16px;
}
.loginContentRight .el-form-item__error {
  margin-top: 5px;
  margin-left: 10px;
}
</style>
